<?php
  require_once('./includes/db.php');

  if(!isset($_SESSION['id']) || empty($_SESSION['id'])){
    header("location:login.php");
    exit;
  }
  $permittedTbl = array('users','countries');

  $tbl = isset($_GET['tbl']) && !empty($_GET['tbl']) ? trim($_GET['tbl']) : '';

  if($tbl == '' || !in_array($tbl, $permittedTbl)){
    jsRedirect('show_all_users.php');
  }

  $get_req_file = date('d-m-Y').'_'.uniqid().'_records.csv';

  $fp = fopen($get_req_file, 'w');

  $allRecords = fetchAll($tbl);

  $colNames = fetchColNames($tbl);
  $colNames = array_map('strtoupper',$colNames);
  fputcsv($fp, $colNames);

  while($ans = mysql_fetch_assoc($allRecords))
  {
    fputcsv($fp, $ans);
  }

  fclose($fp);


  header('Content-Description: File Transfer');
  header('Content-Type: application/force-download');
  header('Content-Length: ' . filesize("$get_req_file"));
  header('Content-Disposition: attachment; filename=' . $get_req_file);
  readfile($get_req_file);
  unlink($get_req_file);






